﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using SoftSource.Common;
using SoftSource.MVVMC;
using SoftSource.Reactive;
using SoftSource.Timecard.Resources;
using SoftSource.Timecard.ViewModelInterfaces;

namespace SoftSource.Timecard.Views
{
    public sealed partial class UserEditorView : UserControl, IView<IUserEditorViewModelConsume>
    {
        public UserEditorView()
        {
            InitializeComponent();

            Loaded += new RoutedEventHandler(UserEditorView_Loaded);
        }

        #region Events

        void UserEditorView_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.ViewModel != null)
            {
                this.Busy.BusyContent = ApplicationStrings.LoadingMessage;
                this.Busy.IsBusy = true;

                this.ViewModel.Load // Load the data required to use this ViewModel
                    .Nullable()
                    .Do(unit => this.Busy.IsBusy = false)
                    .Do(unit => this.UserDataForm.BeginEdit())
                    .Subscribe();
            }
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            if (this.UserDataForm.ValidateItem())
            {
                this.UserDataForm.CommitEdit();
                this.ViewModel.Save
                    .Nullable()
                    .Subscribe();
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.UserDataForm.CancelEdit();
            this.ViewModel.Cancel.TryInvoke();
        }

        private void EditProjects_Click(object sender, RoutedEventArgs e)
        {
            ChildWindow cw = new ChildWindow();
            cw.Title = "Edit Projects";
            cw.Margin = new Thickness(25);

            UIElement view = this.ViewModel.CreateUserProjectEditor.TryInvoke(cw.Close);

            cw.Content = view;
            cw.Show();
        }

        #endregion Events

        #region IView<IUserEditorViewModelConsume> Members

        public IUserEditorViewModelConsume ViewModel
        {
            get { return this.DataContext as IUserEditorViewModelConsume; }
            set { this.DataContext = value; }
        }

        #endregion
    }
}
